package com.xrz.sxm.aj.activity;

import android.content.Intent;
import android.view.View;
import android.widget.EditText;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.lidroid.xutils.view.annotation.ViewInject;
import com.xrz.sxm.aj.base.BaseAct;
import com.xrz.sxm.aj.entity.User;
import com.xrz.sxm.aj.https.Http;
import com.xrz.sxm.aj.https.HttpConst;
import com.xrz.sxm.aj.https.HttpListener;
import com.xrz.sxm.aj.utils.SharedPreferencesUtils;

import java.util.HashMap;
import java.util.Map;

public class Act_Login extends BaseAct {

	@ViewInject(R.id.login_username)
	private EditText m_username_EditText;
	@ViewInject(R.id.login_password)
	private EditText m_pwd_EditText;

	@Override
	protected int setView() {
		return R.layout.act__login;

	}

	@Override
	protected void init() {
		User user= (User) SharedPreferencesUtils.readObject(this,"user");
		if(user!=null){
			m_username_EditText.setText(user.dh);
		}
	}

	@Override
	protected String setTopTitle() {
		return "登陆";
	}

	public void onRegClick(View view) {
		startActivityForResult(new Intent(this, Act_Reg.class), 100);
	}

	public void onLoginClick(View viwe) {
		String username = m_username_EditText.getText().toString().trim();
		String pwd = m_pwd_EditText.getText().toString().trim();
		if (username.equals("") || pwd.equals("")) {
			Toast.makeText(getApplicationContext(), "用户名或密码不能为空！", Toast.LENGTH_SHORT).show();
			return;
		}
		Map<String, String> map = new HashMap<String, String>();
		map.put("dh", username);
		map.put("mm", pwd);
		Http.getInstant().sendRequest(getApplicationContext(), true, HttpConst.URL_LOGIN, map, new HttpListener() {
			@Override
			public void onHttpSuccess(String result) {
				JSONObject object = JSON.parseObject(result);
				int status = object.getIntValue("status");
				String msg = object.getString("msg");
				if (status == -1) {
					Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
				} else {
					JSONArray array = object.getJSONArray("result");
					User user = JSON.parseObject(array.getString(0), User.class);
					SharedPreferencesUtils.saveObject(Act_Login.this, "user", user);
					Toast.makeText(getApplicationContext(), msg, Toast.LENGTH_SHORT).show();
					startActivity(new Intent(getApplicationContext(), Act_Welcome.class));
				}
			}

			@Override
			public void onHttpError(String error) {
				showMessageDialog("提示", "登录失败，请稍候再试");
			}
		});
	}
}
